package com.sp2p.action.front;

import java.math.RoundingMode;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.shove.Convert;
import com.shove.data.DataException;
import com.shove.security.Encrypt;
import com.shove.util.SqlInfusion;
import com.shove.web.util.DesSecurityUtil;
import com.shove.web.util.JSONUtils;
import com.sp2p.constants.IConstants;
import com.sp2p.database.Dao.Views.intentionfund_user;
import com.sp2p.entity.Operator;
import com.sp2p.entity.User;
import com.sp2p.service.BBSRegisterService;
import com.sp2p.service.FinanceService;
import com.sp2p.service.FrontMyPaymentService;
import com.sp2p.service.FundrecordService;
import com.sp2p.service.GoFullAwardService;
import com.sp2p.service.HomeInfoSettingService;
import com.sp2p.service.MyHomeService;
import com.sp2p.service.NewsAndMediaReportService;
import com.sp2p.service.OperationLogService;
import com.sp2p.service.PublicModelService;
import com.sp2p.service.SelectedService;
import com.sp2p.service.SendMailService;
import com.sp2p.service.UserService;
import com.sp2p.service.ValidateService;
import com.sp2p.util.AmountUtil;
import com.sp2p.util.MoneyUtil;

/**
 * @ClassName: FrontMyHomeAction.java
 * @Author: wu.jc
 * @Date: 2014-5-01
 * @Copyright: 
 * @Version: v2.01
 * @Descrb: 我的账户控制层
 */
public class FrontMyHomeAction extends BaseFrontAction {

	public static Log log = LogFactory.getLog(FrontMyHomeAction.class);
	private static final long serialVersionUID = 1L;

	private MyHomeService myHomeService;
	private FinanceService financeService;
	private SelectedService selectedService;
	private List<Map<String, Object>> borrowDeadlineList;
	private Map<String, String> automaticBidMap;
	private List<Operator> checkList;
	private OperationLogService operationLogService;
	private FrontMyPaymentService frontpayService;
	private FundrecordService fundrecordService;
	private NewsAndMediaReportService newsService;
	private UserService userService;
	private SendMailService sendMailService;
	private BBSRegisterService bbsRegisterService;
	private ValidateService validateService;
	private GoFullAwardService goFullAwardService;
	private PublicModelService publicModelService;
	private HomeInfoSettingService homeInfoSettingService;
	
	public FinanceService getFinanceService() {
		return financeService;
	}

	public void setFinanceService(FinanceService financeService) {
		this.financeService = financeService;
	}
	
	public PublicModelService getPublicModelService() {
		return publicModelService;
	}

	public void setPublicModelService(PublicModelService publicModelService) {
		this.publicModelService = publicModelService;
	}

	public void setGoFullAwardService(GoFullAwardService goFullAwardService) {
		this.goFullAwardService = goFullAwardService;
	}

	//账户总览
	public String homeInit() throws Exception {
		int type = Convert.strToInt(request().getParameter("type"), -1);
		User user = (User) session().getAttribute("user");
		
		Map<String, String> accmountStatisMap = myHomeService
				.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);
		
		user.setUsableSum(Convert.strToDouble(accmountStatisMap.get("usableAmount"), 0));
		session().setAttribute("user", user);
		
		Map<String, String> weightingRateMap = myHomeService.queryWeightingRate(user.getId());
		request().setAttribute("weightingRateMap", weightingRateMap);

		Map<String, String> reffereeMap = userService.queryReffereeInfoByInvestor(user.getId());
		request().setAttribute("reffereeMap", reffereeMap);
		
		if(type != -1){
			return "recharge";
		}
		return "success";
	}
	
	public void assetsStatistics() throws Exception {
		User user = (User) session().getAttribute("user");
		
		Map<String, String> accmountStatisMap = myHomeService.queryAccountStatisInfo(user.getId());
		
		JSONUtils.printObject(accmountStatisMap);
	}
	//余额宝7日总收益
	public void yeb7daysTotalRevenue() throws Exception {
		User user = (User) session().getAttribute("user");
		int investId = Convert.strToInt(request("investId"), 0);
		List<Map<String, String>> ylb7DaysIncomeList = myHomeService.queryYeb7daysTotalRevenue(user.getId(),investId);
		JSONObject obj = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		obj.put("ylb7DaysIncomeList", JSONUtils.toJSONArray(ylb7DaysIncomeList));
		JSONUtils.printObject(obj);
	}
	
	public void queryRepayDate() throws Exception{
		User user = (User) session().getAttribute("user");
		Map<String, String> repayDateMap = myHomeService.queryRepayDate(user.getUserName());
		JSONUtils.printObject(repayDateMap);
	}
	
	public void queryRepaySituation() throws Exception{
		User user = (User) session().getAttribute("user");
		List<Map<String, String>> ylbRepayList = myHomeService.queryRepaySituation(user.getUserName(),2);
		List<Map<String, String>> jfbRepayList = myHomeService.queryRepaySituation(user.getUserName(),3);
		List<Map<String, String>> wybRepayList = myHomeService.queryRepaySituation(user.getUserName(),4);
		JSONObject obj = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		obj.put("ylbRepayList", JSONUtils.toJSONArray(ylbRepayList));
		obj.put("jfbRepayList", JSONUtils.toJSONArray(jfbRepayList));
		obj.put("wybRepayList", JSONUtils.toJSONArray(wybRepayList));
		JSONUtils.printObject(obj);
	}
	
	//资产统计
	public String allAssetsStatistics() throws Exception {
		User user = (User) session().getAttribute("user");
		
		Map<String, String> accmountStatisMap = myHomeService.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);
		
		Map<String, String> weightingRateMap = myHomeService.queryWeightingRate(user.getId());
		request().setAttribute("weightingRateMap", weightingRateMap);
		
		return SUCCESS;
	}
	
	public void getWeightingRate() throws Exception {
		User user = (User) session().getAttribute("user");
		
		Map<String, String> accmountStatisMap = myHomeService.getWeightingRate(user.getId());
		
		JSONObject obj = new JSONObject();
		obj.put("result", accmountStatisMap);
		JSONUtils.printObject(obj);
	}
	
	//投资记录
	public void investYebRecordSum() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryInvestYebRecord(user.getId(), pageBean);
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("lists", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
	}
	public void investYebRecord() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		myHomeService.queryInvestYebRecordDetail(user.getId(), pageBean);
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("lists", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
	}
	public String investRecordYebDetail() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		long id = Convert.strToLong(request("id"), -1L);
		
		Map<String, String> map = myHomeService.queryInvestYebRecordDetail(id,user.getId());
		request().setAttribute("map", map);
		return SUCCESS;
	}
	
	public void investProductRecord() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		int status = Convert.strToInt(request("status"), 0);
		int borrowProduct = Convert.strToInt(request("borrowProduct"), -1);
		
		myHomeService.queryInvestProductRecord(borrowProduct,status,user.getId(), pageBean);
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("lists", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		
		JSONUtils.printObject(obj);
	}
	
	public String investRecordDetail() throws Exception {
		User user = (User) session().getAttribute("user");
		pageBean.setPageNum(1);
		pageBean.setPageSize(100);
		int investId = Convert.strToInt(request("id"), -1);
		myHomeService.queryInvestRecordDetail(investId,user.getId(), pageBean);
		
		List<Map<String,Object>> pageList = pageBean.getPage();
		if(pageList!=null&&pageList.size()>0){
			Map<String,Object> map = pageList.get(0);
			request().setAttribute("map", map);
		}
		
		request().setAttribute("forPaymentMap", pageBean.getPage());
		
		return SUCCESS;
	}
	
	//自动投资
	public Map<String, String> getAutomaticBidMap() throws Exception {
		if (automaticBidMap == null) {
			// 自动投标设置
			User user = (User) session().getAttribute("user");
			automaticBidMap = myHomeService.queryAutomaticBid(user.getId());
			checkList = new ArrayList<Operator>();
			if (automaticBidMap != null) {
				// 设置ckBoxList的选中值
				String borrowWay = automaticBidMap.get("borrowWay");
				String[] ckList = borrowWay.split(",");
				if (ckList.length > 0) {
					for (String ck : ckList) {
						checkList.add(new Operator(ck, ""));
					}
				}
			}
		}
		return automaticBidMap;
	}
	
	public String automaticBidInit() throws SQLException, DataException {
		return "success";
	}
	
	public String automaticBidSet() throws Exception {
		String bidStatus =SqlInfusion.FilteSqlInfusion( paramMap.get("s") == null ? "1" : paramMap.get("s"));
		long bidStatusLong = Convert.strToLong(bidStatus, 1);
		JSONObject obj = new JSONObject();
		User user = (User) session().getAttribute("user");
		long returnId = -1;
		returnId = myHomeService.automaticBidSet(bidStatusLong, user.getId());

		if (returnId <= 0) {
			obj.put("msg", "未保存自动投标设置");
		} else {
			obj.put("msg", 1);
		}
		JSONUtils.printObject(obj);
		return null;
	}

	public String automaticBidModify() throws Exception {
		JSONObject obj = new JSONObject();
		User user = (User) session().getAttribute("user");
		long returnId = -1;
		System.out.println(123);
		double usableSum = Convert.strToDouble(paramMap.get("usableSum"), 0);
		String bidAmount = paramMap.get("bidAmount") == null ? "" : paramMap
				.get("bidAmount");
		String rateStart =SqlInfusion.FilteSqlInfusion( paramMap.get("rateStart") == null ? "" : paramMap
				.get("rateStart"));
		String rateEnd ="18";
//		String rateEnd = SqlInfusion.FilteSqlInfusion(paramMap.get("rateEnd") == null ? "" : paramMap
//				.get("rateEnd"));
		/*String deadlineStart = SqlInfusion.FilteSqlInfusion(paramMap.get("deadlineStart") == null ? ""
				: paramMap.get("deadlineStart"));*/
		String deadlineStart ="-1";
		String deadlineEnd = SqlInfusion.FilteSqlInfusion(paramMap.get("deadlineEnd") == null ? ""
				: paramMap.get("deadlineEnd"));
		String creditStart = SqlInfusion.FilteSqlInfusion(paramMap.get("creditStart") == null ? ""
				: paramMap.get("creditStart"));
		String creditEnd = SqlInfusion.FilteSqlInfusion(paramMap.get("creditEnd") == null ? "" : paramMap
				.get("creditEnd"));
		String remandAmount = SqlInfusion.FilteSqlInfusion(paramMap.get("remandAmount") == null ? ""
				: paramMap.get("remandAmount"));
//		String borrowWay = paramMap.get("borrowWay") == null ? "" : paramMap
//				.get("borrowWay");
		Double bidAmountDouble = Convert.strToDouble(bidAmount, 0);
		Double rateStartDouble = Convert.strToDouble(rateStart, 0);
		Double rateEndDouble = Convert.strToDouble(rateEnd, 0);
		Double deadlineStartDouble = Convert.strToDouble(deadlineStart, 0);
		Double deadlineEndDouble = Convert.strToDouble(deadlineEnd, 0);
		Double creditStartDouble = Convert.strToDouble(creditStart, 0);
		Double creditEndDouble = Convert.strToDouble(creditEnd, 0);
		Double remandAmountDouble = Convert.strToDouble(remandAmount, 0);
		boolean bool=true;
		try{
			double b = Double.parseDouble(remandAmount);
		}catch(Exception e){
			bool=false;
		}
		
		/*if (StringUtils.isBlank(bidAmount)) {
			obj.put("msg", "每次投标金额不可为空");
			JSONUtils.printObject(obj);
			return null;
		} else if (bidAmountDouble == 0) {
			obj.put("msg", "每次投标金额格式错误");
			JSONUtils.printObject(obj);
			return null;
		} else if (bidAmountDouble < 50) {
			obj.put("msg", "每次投标金额不能低于50元");
			JSONUtils.printObject(obj);
			return null;
		}*/
		if (StringUtils.isBlank(rateStart)) {
			obj.put("msg", "利率范围开始不可为空");
			JSONUtils.printObject(obj);
			return null;
		} else if (rateStartDouble == 0) {
			obj.put("msg", "利率范围开始格式错误");
			JSONUtils.printObject(obj);
			return null;
		} else if (rateStartDouble < 1 || rateStartDouble > 24) {
			obj.put("msg", "年利率范围1%-24%，请在此范围内选择利率");
			JSONUtils.printObject(obj);
			return null;
		}
		if (StringUtils.isBlank(rateEnd)) {
			obj.put("msg", "利率范围结束不可为空");
			JSONUtils.printObject(obj);
			return null;
		} else if (rateEndDouble == 0) {
			obj.put("msg", "利率范围结束格式错误");
			JSONUtils.printObject(obj);
			return null;
		} else if (rateEndDouble < 1 || rateEndDouble > 24) {
			obj.put("msg", "年利率范围1%-24%，请在此范围内选择利率");
			JSONUtils.printObject(obj);
			return null;
		}
		if (StringUtils.isBlank(remandAmount)) {
			obj.put("msg", "账户保留金额不可为空");
			JSONUtils.printObject(obj);
			return null;
		} else if (bool==false) {
			obj.put("msg", "账户保留金额格式错误");
			JSONUtils.printObject(obj);
			return null;
		}
//		if (StringUtils.isBlank(borrowWay)) {
//			obj.put("msg", "请勾选借款类型");
//			JSONUtils.printObject(obj);
//			return null;
//		}	
		/*if (bidAmountDouble > usableSum - remandAmountDouble) {
			obj.put("msg", "投标金额不能大于(可用余额 - 保底金额)");
			JSONUtils.printObject(obj);
			return null;
		}*/
		returnId = myHomeService.automaticBidModify(bidAmountDouble,
				rateStartDouble, rateEndDouble, deadlineStartDouble,
				deadlineEndDouble, creditStartDouble, creditEndDouble,
				remandAmountDouble, user.getId()/*, borrowWay*/);

		if (returnId <= 0) {
			obj.put("msg", IConstants.ACTION_FAILURE);
		} else {
			obj.put("msg", IConstants.ACTION_SUCCESS);
		}
		JSONUtils.printObject(obj);
		return null;

	}
	
	public String viewCreditRightsContract() throws Exception {
		User user = (User)session().getAttribute("user");
		String ids = Convert.strToStr(request("ids"), "").replace("-", ",");
		Map<String,String> personInfo = userService.queryPersonById(user.getId());
		List<Map<String, Object>> loanDetailList = myHomeService.queryLoanAssignment(ids);
		
		Double tradeValueSum = 0.00;
		Double soldPriceSum = 0.00;
		for (Map<String, Object> loanMap : loanDetailList) {
			tradeValueSum += Convert.strToDouble(loanMap.get("tradeValue").toString(), 0.00);
			soldPriceSum += Convert.strToDouble(loanMap.get("soldPrice").toString(), 0.00);
		}
		DecimalFormat df_two = new DecimalFormat("#0.00");
		
		request().setAttribute("investorIdNo", personInfo.get("idNo"));
		request().setAttribute("loanDetailList", loanDetailList);
		request().setAttribute("tradeValueSum", df_two.format(tradeValueSum));
		request().setAttribute("soldPriceSum", df_two.format(soldPriceSum));
		return SUCCESS;
	}
	
	
	//借款协议
	public String contractDetail() throws Exception {
		User user = (User)session().getAttribute("user");
		long investId = Convert.strToLong(request().getParameter("investId"), -1);
		if(investId < 0 || user.getId() < 0){
			return "blank";
		}
		Map<String, String> investDetailMap = myHomeService.queryInvestById(investId, user.getId()); //投资信息
		if(investDetailMap == null){
			return "blank";
		}
		
		// 借款详情
		Long parentBId = Convert.strToLong(investDetailMap.get("parentBId"),0);
		Long borrowId = Convert.strToLong(investDetailMap.get("borrowId"),0);
		Map<String, String> borrowDetailMap = financeService.queryBorrowDetailById(parentBId);//父标
		if(borrowDetailMap!=null){
			Double borrowSum = Convert.strToDouble(borrowDetailMap.get("borrowSum"),-1.00);
			String borrowSumChinese = MoneyUtil.amountToChinese(borrowSum);
			borrowDetailMap.put("borrowSumChinese", borrowSumChinese);
			//收益计算
			int paymentMode = Convert.strToInt(borrowDetailMap.get("paymentMode"), -1);
			int isDayThe = Convert.strToInt(borrowDetailMap.get("isDayThe"), -1);
			int deadline = Convert.strToInt(borrowDetailMap.get("deadline"), -1);
			Double annualRate = Convert.strToDouble(borrowDetailMap.get("annualRate"), 0.00);
			AmountUtil au = new AmountUtil();
			Map<String, String> repayMapList = new HashMap<String, String>();
			if (paymentMode == 1) {
				// 按月等额还款
				repayMapList = au.earnCalculateMonth(borrowSum,borrowSum,annualRate,deadline,0.00,isDayThe,0,0.00);
			} else if (paymentMode == 2) {
				// 每月还息到期还本
				repayMapList = au.earnCalculateSum(borrowSum,borrowSum,annualRate,deadline,0.00,isDayThe,0);
			} else if (paymentMode == 4) {
				// 一次性还本付息
				repayMapList = au.earnCalculateOne(borrowSum,borrowSum,annualRate,deadline,0.00,isDayThe,0,0.00);
			}	
			Double monInterest = Convert.strToDouble(repayMapList.get("monInterest"),0.00);
			borrowDetailMap.put("monInterest", repayMapList.get("monInterest"));
			borrowDetailMap.put("monInterestChinese", MoneyUtil.amountToChinese(monInterest));
		}
		Map<String, String> cBorrowDetailMap = financeService.queryBorrowDetailById(borrowId);//子标
		//担保人信息
		String roletype = borrowDetailMap.get("roletype");
		if(roletype.equals("1")){
			borrowDetailMap.put("dname", borrowDetailMap.get("personname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("idNo"));
		}else{
			borrowDetailMap.put("dname", borrowDetailMap.get("companyname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("businesslicence"));
		}
		// 借款人资料
		Map<String, String> borrowUserMap = financeService.queryUserInfoById(parentBId);
		
		request().setAttribute("investDetailMap", investDetailMap);
		request().setAttribute("borrowDetailMap", borrowDetailMap);
		request().setAttribute("cBorrowDetailMap", cBorrowDetailMap);
		request().setAttribute("borrowUserMap", borrowUserMap);
		
		//不同担保机构对应不同协议
		if(borrowDetailMap.get("agent").equals("75")){
			return "jrl";
		}
		
		return "success";
	}
	
	//余额宝借款合同
	public String yebhtContractDetail() throws Exception {
		User user = (User)session().getAttribute("user");
		long investId = Convert.strToLong(request().getParameter("investId"), -1);
		if(investId < 0 || user.getId() < 0){
			return "blank";
		}
		Map<String, String> investDetailMap = myHomeService.queryYebInvestById(investId, user.getId()); //投资信息
		if(investDetailMap == null){
			return "blank";
		}
		// 借款详情
		Long parentBId = Convert.strToLong(investDetailMap.get("borrowId"),0);
		Map<String, String> borrowDetailMap = financeService.queryBorrowDetailById(parentBId);//父标
		if(borrowDetailMap!=null){
			Double borrowSum = Convert.strToDouble(borrowDetailMap.get("borrowSum"),-1.00);
			Double annualRate=Convert.strToDouble(borrowDetailMap.get("annualRate"),-1.00);
			Double dayInterest= borrowSum*annualRate/100/360;
			dayInterest=(double)(Math.round(dayInterest*100)/100.0); 
			String borrowSumChinese = MoneyUtil.amountToChinese(borrowSum);
			borrowDetailMap.put("borrowSumChinese", borrowSumChinese);
			Map<String, String> repayMapList = new HashMap<String, String>();
			borrowDetailMap.put("dayInterest", Double.toString(dayInterest));
			borrowDetailMap.put("monInterestChinese", MoneyUtil.amountToChinese(dayInterest));
		}

		//担保人信息
		String roletype = borrowDetailMap.get("roletype");
		if(roletype.equals("1")){
			borrowDetailMap.put("dname", borrowDetailMap.get("personname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("idNo"));
		}else{
			borrowDetailMap.put("dname", borrowDetailMap.get("companyname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("businesslicence"));
		}
		// 借款人资料
		Map<String, String> borrowUserMap = financeService.queryUserInfoById(parentBId);
		
		request().setAttribute("investDetailMap", investDetailMap);
		request().setAttribute("borrowDetailMap", borrowDetailMap);
		request().setAttribute("borrowUserMap", borrowUserMap);
		
		return "success";
	}
	
	public String exportLoanAgree() throws Exception {
		long investId = Convert.strToLong(request().getParameter("investId"), -1);
		String userId = Convert.strToStr(request().getParameter("userId"), "");
		long uid = Convert.strToLong(Encrypt.decrypt3DES(userId, "I4008lOve893gOfUll983"), -1); //解密加密串
		if(investId < 0 || uid < 0){
			return "blank";
		}
		
		Map<String, String> investDetailMap = myHomeService.queryInvestById(investId, uid); //投资信息
		if(investDetailMap == null){
			return "blank";
		}
		// 借款详情
		Long parentBId = Convert.strToLong(investDetailMap.get("parentBId"),0);
		Long borrowId = Convert.strToLong(investDetailMap.get("borrowId"),0);
		Map<String, String> borrowDetailMap = financeService.queryBorrowDetailById(parentBId);//父标
		if(borrowDetailMap!=null){
			Double borrowSum = Convert.strToDouble(borrowDetailMap.get("borrowSum"),-1.00);
			String borrowSumChinese = MoneyUtil.amountToChinese(borrowSum);
			borrowDetailMap.put("borrowSumChinese", borrowSumChinese);
			//收益计算
			int paymentMode = Convert.strToInt(borrowDetailMap.get("paymentMode"), -1);
			int isDayThe = Convert.strToInt(borrowDetailMap.get("isDayThe"), -1);
			int deadline = Convert.strToInt(borrowDetailMap.get("deadline"), -1);
			Double annualRate = Convert.strToDouble(borrowDetailMap.get("annualRate"), 0.00);
			AmountUtil au = new AmountUtil();
			Map<String, String> repayMapList = new HashMap<String, String>();
			if (paymentMode == 1) {
				// 按月等额还款
				repayMapList = au.earnCalculateMonth(borrowSum,borrowSum,annualRate,deadline,0.00,isDayThe,0,0.00);
			} else if (paymentMode == 2) {
				// 每月还息到期还本
				repayMapList = au.earnCalculateSum(borrowSum,borrowSum,annualRate,deadline,0.00,isDayThe,0);
			} else if (paymentMode == 4) {
				// 一次性还本付息
				repayMapList = au.earnCalculateOne(borrowSum,borrowSum,annualRate,deadline,0.00,isDayThe,0,0.00);
			}	
			
			StringBuffer tdmonInterest = new StringBuffer();
			String interestAmount = "￥" + repayMapList.get("monInterest");
			String[] interestAmountstr = interestAmount.split("\\.");
			char[] interestAmountstrs1 = String.format("%8s", interestAmountstr[0]).toCharArray();
			char[] interestAmountstrs2 = interestAmountstr[1].toCharArray();
			for (int i = 0; i <= 7; i++) {
				tdmonInterest.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+interestAmountstrs1[i]+"</div></td>");
			}
			tdmonInterest.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+interestAmountstrs2[0]+"</div></td>");
			tdmonInterest.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+interestAmountstrs2[1]+"</div></td>");
			
			borrowDetailMap.put("tdmonInterest", tdmonInterest.toString());
			Double monInterest = Convert.strToDouble(repayMapList.get("monInterest"),0.00);
			borrowDetailMap.put("monInterestChinese", MoneyUtil.amountToChinese(monInterest));
		}
		
		StringBuffer tdBorrowSum = new StringBuffer();
		String amount = "￥" + borrowDetailMap.get("borrowSum");
		String[] str = amount.split("\\.");
		char[] strs = String.format("%8s", str[0]).toCharArray();
		for (int i = 0; i <= 7; i++) {
			tdBorrowSum.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+strs[i]+"</div></td>");
		}
		borrowDetailMap.put("tdBorrowSum",tdBorrowSum.toString());
		
		Map<String, String> cBorrowDetailMap = financeService.queryBorrowDetailById(borrowId);//子标
		
		//担保人信息
		String roletype = borrowDetailMap.get("roletype");
		if(roletype.equals("1")){
			borrowDetailMap.put("dname", borrowDetailMap.get("personname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("idNo"));
		}else{
			borrowDetailMap.put("dname", borrowDetailMap.get("companyname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("businesslicence"));
		}
		// 借款人资料
		Map<String, String> borrowUserMap = financeService.queryUserInfoById(parentBId);
		
		request().setAttribute("investDetailMap", investDetailMap);
		request().setAttribute("borrowDetailMap", borrowDetailMap);
		request().setAttribute("cBorrowDetailMap", cBorrowDetailMap);
		request().setAttribute("borrowUserMap", borrowUserMap);
		
		//不同担保机构对应不同协议
		if(borrowDetailMap.get("agent").equals("75")){
			return "jrl";
		}
		
		return "success";
	}
	
	public String yebContractDetail() throws Exception {
		User user = (User)session().getAttribute("user");
		long investId = Convert.strToLong(request().getParameter("investId"), -1);

		Map<String, String> yebInvestDetailMap = financeService.queryYebInvestByInvestId(user.getId(),investId); //余额宝投资信息
		if(yebInvestDetailMap != null){
			Double investAmount = Convert.strToDouble(yebInvestDetailMap.get("InvestAmount"),-1.00);
			String investAmountChinese = MoneyUtil.amountToChinese(investAmount);
			yebInvestDetailMap.put("investAmountChinese", investAmountChinese);
		}
		request().setAttribute("yebInvestDetailMap", yebInvestDetailMap);
		return SUCCESS;
	}
	
	public String exportYebLoanAgree() throws Exception {
		String userId = Convert.strToStr(request().getParameter("userId"), "");
		long uid = Convert.strToLong(Encrypt.decrypt3DES(userId, "I4008lOve893gOfUll983"), -1); //解密加密串

		long investId = Convert.strToLong(request().getParameter("investId"), -1);
		if(investId < 0 || uid  < 0){
			return "blank";
		}
		Map<String, String> yebInvestDetailMap = financeService.queryYebInvestByInvestId(uid,investId); //余额宝投资信息
		if(yebInvestDetailMap != null){
			Double investAmount = Convert.strToDouble(yebInvestDetailMap.get("InvestAmount"),-1.00);
			String investAmountChinese = MoneyUtil.amountToChinese(investAmount);
			yebInvestDetailMap.put("investAmountChinese", investAmountChinese);
			
			StringBuffer sbYebInvestAmount = new StringBuffer();
			String interestAmount = "￥" + yebInvestDetailMap.get("InvestAmount");
			String[] interestAmountstr = interestAmount.split("\\.");
			char[] interestAmountstrs1 = String.format("%7s", interestAmountstr[0]).toCharArray();
			char[] interestAmountstrs2 = interestAmountstr[1].toCharArray();
			for (int i = 0; i <= 6; i++) {
				sbYebInvestAmount.append("<td align=\"center\">"+interestAmountstrs1[i]+"</td>");
			}
			sbYebInvestAmount.append("<td align=\"center\">"+interestAmountstrs2[0]+"</td>");
			sbYebInvestAmount.append("<td align=\"center\">"+interestAmountstrs2[1]+"</td>");
			yebInvestDetailMap.put("sbYebInvestAmount", sbYebInvestAmount.toString());
		}else{
			return "blank";
		}
		request().setAttribute("yebInvestDetailMap", yebInvestDetailMap);
		return SUCCESS;
	}
	
	public String exportYebLoanHt() throws Exception {
		String userId = Convert.strToStr(request().getParameter("userId"), "");
		long uid = Convert.strToLong(Encrypt.decrypt3DES(userId, "I4008lOve893gOfUll983"), -1); //解密加密串
		long investId = Convert.strToLong(request().getParameter("investId"), -1);
		if(investId < 0 || uid  < 0){
			return "blank";
		}

		Map<String, String> investDetailMap = myHomeService.queryYebInvestById(investId, uid); //投资信息
		if(investDetailMap == null){
			return "blank";
		}
		
		// 借款详情
		Long parentBId = Convert.strToLong(investDetailMap.get("borrowId"),0);
		Map<String, String> borrowDetailMap = financeService.queryBorrowDetailById(parentBId);//父标
		if(borrowDetailMap!=null){
			Double borrowSum = Convert.strToDouble(borrowDetailMap.get("borrowSum"),-1.00);
			Double annualRate=Convert.strToDouble(borrowDetailMap.get("annualRate"),-1.00);
			Double dayInterest= borrowSum*annualRate/100/360;
			dayInterest=(double)(Math.round(dayInterest*100)/100.0); 
			String borrowSumChinese = MoneyUtil.amountToChinese(borrowSum);
			borrowDetailMap.put("borrowSumChinese", borrowSumChinese);
			borrowDetailMap.put("dayInterestChinese", MoneyUtil.amountToChinese(dayInterest));
			
			//借款金额 表格
			StringBuffer tdBorrowSum = new StringBuffer();
			String amount = "￥" + borrowDetailMap.get("borrowSum");
			String[] str = amount.split("\\.");
			char[] strs = String.format("%8s", str[0]).toCharArray();
			for (int i = 0; i <= 7; i++) {
				tdBorrowSum.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+strs[i]+"</div></td>");
			}
			borrowDetailMap.put("tdBorrowSum",tdBorrowSum.toString());
			
			//每日利息表格
			StringBuffer tdayInterest = new StringBuffer();
			String interestAmount = "￥" + dayInterest;
			String[] interestAmountstr = interestAmount.split("\\.");
			char[] interestAmountstrs1 = String.format("%8s", interestAmountstr[0]).toCharArray();
			char[] interestAmountstrs2 = interestAmountstr[1].toCharArray();
			for (int i = 0; i <= 7; i++) {
				tdayInterest.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+interestAmountstrs1[i]+"</div></td>");
			}
			tdayInterest.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+interestAmountstrs2[0]+"</div></td>");
			tdayInterest.append("<td bgcolor=\"#FFFFFF\" align=\"center\"><div>"+interestAmountstrs2[1]+"</div></td>");
			
			borrowDetailMap.put("tdayInterest", tdayInterest.toString());
		}

		//担保人信息
		String roletype = borrowDetailMap.get("roletype");
		if(roletype.equals("1")){
			borrowDetailMap.put("dname", borrowDetailMap.get("personname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("idNo"));
		}else{
			borrowDetailMap.put("dname", borrowDetailMap.get("companyname"));
			borrowDetailMap.put("licenceNo", borrowDetailMap.get("businesslicence"));
		}
		// 借款人资料
		Map<String, String> borrowUserMap = financeService.queryUserInfoById(parentBId);
		
		request().setAttribute("investDetailMap", investDetailMap);
		request().setAttribute("borrowDetailMap", borrowDetailMap);
		request().setAttribute("borrowUserMap", borrowUserMap);
		return SUCCESS;
	}	
	
	public String gofullAward() throws Exception {
		User user=(User)session().getAttribute("user");
		int reffereeType = user.getReffereeType();
		if(reffereeType <= 1 ) {
			return "blank";
		}
		Map<String,String> awardNotSettledMap=goFullAwardService.queryAwardNotSettled(user.getId());
		Map<String,String> acountMap=goFullAwardService.queryAward(user.getId());
		Map<String,String> userReffereeMap=myHomeService.queryUserReffereeCounts(user.getUserName());
		Map<String,String> userReffereeCapitalMap=myHomeService.queryUserReffereeCapital(user.getId());
		int counts = Convert.strToInt(userReffereeMap.get("counts"), 0);
		String userReffereeCapital = "0.00";
		if(userReffereeCapitalMap != null){
			userReffereeCapital = Convert.strToStr(userReffereeCapitalMap.get("amountSum"), "0.00");
		}
		String notSettledAcount=awardNotSettledMap.get("awardMoney");
		String acount=acountMap.get("awardMoney");
	    String uri=getPath();
	    DesSecurityUtil des = new DesSecurityUtil();
	    String userI = des.encrypt(this.getUserId()+"");
		request().setAttribute("url", uri);
		request().setAttribute("userId", userI);
		request().setAttribute("notSettledAcount", notSettledAcount);
		request().setAttribute("acount", acount);
		request().setAttribute("userReffereeCounts", counts);
		request().setAttribute("userReffereeCapital", userReffereeCapital);
		return SUCCESS;
	}
	
	public String myElite() throws Exception {
		User user=(User)session().getAttribute("user");
		
		Map<String, String> availableEliteMap = myHomeService.queryAvailableElite(user.getId()); //体验金余额
		Map<String, String> tEliteInterestMap = myHomeService.queryTdEliteInterest(user.getId());//今日收益
		Map<String, String> expectInterestMap = myHomeService.queryExpectEliteInterest(user.getId());//待领取收益
		Map<String, String> lastEliteProduct = myHomeService.queryLastEliteProduct();//体验金理财项目
		
		List<Map<String, String>> eliteRecords = myHomeService.queryEliteRecord(user.getId()); //获取记录
		List<Map<String, String>> eliteInvestRecords = myHomeService.queryEliteInvestRecord(user.getId()); //投资记录
		
		request().setAttribute("availableEliteMap", availableEliteMap);
		request().setAttribute("tEliteInterestMap", tEliteInterestMap);
		request().setAttribute("expectInterestMap", expectInterestMap);
		request().setAttribute("lastEliteProduct", lastEliteProduct);
		request().setAttribute("eliteRecords", eliteRecords);
		request().setAttribute("eliteInvestRecords", eliteInvestRecords);
		return SUCCESS;
	}
	
	public void myEliteInvest() throws Exception {
		User user=(User)session().getAttribute("user");
		JSONObject obj = new JSONObject();
		
		//判断可用体验余额是否大于0
		Map<String, String> aElite = myHomeService.queryAvailableElite(user.getId()); 
		double availableElite = Convert.strToDouble(aElite.get("amount"), -1d);
		if (availableElite <= 0){
			return;
		}
		
		//体验金投资
		Map<String,String> result = myHomeService.addEliteInvest(user.getId());
	    String resultMSG = result.get("ret_desc");
	    if("".equals(resultMSG)){
			obj.put("msg", "success");
	    }else{
	    	obj.put("msg", result.get("ret_desc")+"");
	    }
	    
	    Map<String, String> availableEliteMap = myHomeService.queryAvailableElite(user.getId()); //体验金余额
		Map<String, String> tEliteInterestMap = myHomeService.queryTdEliteInterest(user.getId());//今日收益
		Map<String, String> expectInterestMap = myHomeService.queryExpectEliteInterest(user.getId());//待领取收益
		Map<String, String> lastEliteProduct = myHomeService.queryLastEliteProduct();//体验金理财项目
		
		obj.put("leftElite",availableEliteMap.get("amount"));
		obj.put("todayInterest",tEliteInterestMap.get("interest"));
		obj.put("expectInterest",expectInterestMap.get("expectInterest"));
		
		//计算投资到期日
		int deadline = Convert.strToInt(lastEliteProduct.get("deadline"), 0);
		int isDayThe = Convert.strToInt(lastEliteProduct.get("isDayThe"), 0);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        if(isDayThe == 1){
        	c.add(Calendar.MONTH, deadline);
        }else if(isDayThe == 2){
        	c.add(Calendar.DAY_OF_MONTH, deadline);
        }
        obj.put("settleDate",sf.format(c.getTime()));
        
		
		JSONUtils.printObject(obj);
	}
	
	public void eliteReceiveAll() throws Exception {
		User user=(User)session().getAttribute("user");
		JSONObject obj = new JSONObject();
		
		//判断待领取收益是否大于0
		Map<String, String> eInterest= myHomeService.queryExpectEliteInterest(user.getId());
		double expectInterest = Convert.strToDouble(eInterest.get("expectInterest"), -1d);
		if (expectInterest <= 0){
			return;
		}
		
		//领取所有收益
		Map<String,String> result = myHomeService.eliteReceiveAll(user.getId());
	    String resultMSG = result.get("ret_desc");
	    if("".equals(resultMSG)){
			obj.put("msg", "success");
	    }else{
	    	obj.put("msg", result.get("ret_desc")+"");
	    }
	    
	    Map<String, String> tEliteInterestMap = myHomeService.queryTdEliteInterest(user.getId());//今日收益
		Map<String, String> expectInterestMap = myHomeService.queryExpectEliteInterest(user.getId());//待领取收益
		Map<String, String> availableEliteMap = myHomeService.queryAvailableElite(user.getId()); //体验金余额
	    
		obj.put("leftElite",availableEliteMap.get("amount"));
		obj.put("todayInterest",tEliteInterestMap.get("interest"));
		obj.put("expectInterest",expectInterestMap.get("expectInterest"));
		
		JSONUtils.printObject(obj);
	}
	
	public String voucherCenter() throws Exception {
		return SUCCESS;
	}
	
	public void getAllVoucherList() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		
		myHomeService.queryAllVoucherList(user.getId(), pageBean);
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("voList", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("voList", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		
		JSONUtils.printObject(obj);
	}
	
	public void getVoucherRecordsById() throws Exception {
		User user = (User) session().getAttribute("user");
		String voucherId = SqlInfusion.FilteSqlInfusion(paramMap.get("voucherId") == null?"":paramMap.get("voucherId"));
		long voucherIdLong = Convert.strToLong(voucherId, -1);
		
		JSONObject obj = new JSONObject();
		List<Map<String, Object>> voucherRecordsList =  myHomeService.getVoucherRecordsById(user.getId(),voucherIdLong);
		obj.put("voList", voucherRecordsList);
		JSONUtils.printObject(obj);
	}
	
	public void redeemVoucherCode() throws Exception {
		User user=(User)session().getAttribute("user");
		JSONObject obj = new JSONObject();
		if(null == user){
			obj.put("status", -1);
			obj.put("msg", "用户未登录");
			JSONUtils.printObject(obj);
			return;
		}
		
		String redemptionCode = SqlInfusion.FilteSqlInfusion(paramMap.get("redemptionCode"));
		if(redemptionCode.length() <= 0){
			obj.put("status", -1);
			obj.put("msg", "兑换码格式不正确");
			JSONUtils.printObject(obj);
			return;
		}
		
		//兑换共富券
		Map<String,String> result = myHomeService.redeemVoucherCode(user.getId(),redemptionCode);
	    String resultMSG = result.get("ret_desc");
	    if("".equals(resultMSG)){
			obj.put("status", 1);
	    }else{
	    	obj.put("status", -1);
	    	obj.put("msg", result.get("ret_desc")+"");
	    }
		JSONUtils.printObject(obj);
	}

	/**
	 * 好友邀请统计初始化
	 * @return
	 * @throws Exception
	 */
	public String inviteAccountCenter() throws Exception{
		User user=(User)session().getAttribute("user");
		int reffereeType = user.getReffereeType();
		if(reffereeType > 1 ) {
			return "blank";
		}
		String uri=getPath();
	    DesSecurityUtil des = new DesSecurityUtil();
	    String userI = des.encrypt(this.getUserId()+"");
		request().setAttribute("url", uri);
		request().setAttribute("userId", userI);
		
		return SUCCESS;
	}
	
	public void inviteUserInfos() throws Exception{
		User user=(User)session().getAttribute("user");
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("currentPage")));
		pageBean.setPageSize(Convert.strToInt(request("pageSize"), 10));
		
		myHomeService.queryUserReffereeInfo(user.getUserName(), pageBean);
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("lists", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
	    
	}
	
	public void queryUserCapitalGuard() throws Exception{
		User user=(User)session().getAttribute("user");
		
		String username = SqlInfusion.FilteSqlInfusion(paramMap.get("username"));
		String capitalLevel = SqlInfusion.FilteSqlInfusion(paramMap.get("capitalLevel"));
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(paramMap.get("currentPage")));
		pageBean.setPageSize(Convert.strToInt(paramMap.get("pageSize"), 10));
		
		myHomeService.queryUserCapitalGuard(username, capitalLevel, user.getUserName(), pageBean);
		
		JSONObject obj = new JSONObject();
		if( pageBean.getTotalNum() > 0){
			obj.put("lists", JSONUtils.toJSONArray(pageBean.getPage()));
		}else{
			obj.put("lists", "");
		}
		obj.put("currentPage", pageBean.pageNum);
		obj.put("pageCount", pageBean.getTotalPageNum());
		obj.put("recordCount", pageBean.getTotalNum());
		JSONUtils.printObject(obj);
	    
	}
	
	public void reffereeCapital15days() throws Exception {
		User user = (User) session().getAttribute("user");
		int investId = Convert.strToInt(request("investId"), 0);
		List<Map<String, String>> ylb7DaysIncomeList = myHomeService.reffereeCapital15days(user.getId());
		JSONObject obj = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		obj.put("reffereeCapital7daysList", JSONUtils.toJSONArray(ylb7DaysIncomeList));
		JSONUtils.printObject(obj);
	}
	
	
	
	
	
	
	
	
//v1.0-----------------------------------------------------------------------------	
	/**
	 * @throws Exception
	 * @MethodName: homeInit
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-18 下午08:53:19
	 * @Return:
	 * @Descb: 借款人主页初始化
	 * @Throws:
	 */
	public String jkperHomeInit() throws Exception {
		User user = (User) session().getAttribute("user");
		
		//公告
		List<Map<String,Object>> newsList = new ArrayList<Map<String,Object>>();
		pageBean.setPageSize(5);
		newsService.frontQueryNewsPage(pageBean);
		newsList = pageBean.getPage();
		pageBean.setPage(null);
		request().setAttribute("newsList", newsList);
		
		Map<String, String> repayBorrowMap = myHomeService.queryRepaymentByBorrowPer(user
				.getId());
		String repayPeriod="";
		double repay=0d;
		if(null!=repayBorrowMap&&repayBorrowMap.get("repayPeriod")!=null&&repayBorrowMap.get("repayPeriod").length()>0){
			repayPeriod=repayBorrowMap.get("repayPeriod");
			repay=(Double.parseDouble(repayPeriod.split("/")[0])-1)/Double.parseDouble(repayPeriod.split("/")[1]);
			repayBorrowMap.put("repay", String.format("%.2f",repay*100));
		}
		request().setAttribute("repayBorrowMap", repayBorrowMap);
		
		Map<String, String> borrowPerStaMap = myHomeService.queryBorrowPerStatisc(user.getId());
		
		
		
		List<Map<String, Object>> fundMap = myHomeService.queryFundRecord(user.getId());
		request().setAttribute("fundMap", fundMap);
		
		List<Map<String, Object>> threeRecordMap = myHomeService.queryFundRecordThree(user.getId());
		request().setAttribute("threeRecordMap", threeRecordMap);
		
		Map<String, String> userStatisMap = myHomeService.queryBorrowPerStatis(user
				.getId());
		double payCount=0d;
		double sypayCount=0d;
		//资产统计计算（左）
		if(null!=userStatisMap&&null!=userStatisMap.get("borrowAmount")&&userStatisMap.get("borrowAmount").length()>0
		 &&null!=borrowPerStaMap&&null!=borrowPerStaMap.get("recivedInterest")&&borrowPerStaMap.get("recivedInterest").length()>0){
			payCount=Double.parseDouble(userStatisMap.get("borrowAmount"))+Double.parseDouble(borrowPerStaMap.get("recivedInterest"));
			borrowPerStaMap.put("payCount", String.format("%.2f",payCount));
			if(null!=borrowPerStaMap.get("hasPrincipal")&&borrowPerStaMap.get("hasPrincipal").length()>0
				&&null!=borrowPerStaMap.get("hasInterest")&&borrowPerStaMap.get("hasInterest").length()>0
				&&null!=borrowPerStaMap.get("recivedFI")&&borrowPerStaMap.get("recivedFI").length()>0){
				sypayCount=payCount-Double.parseDouble(borrowPerStaMap.get("hasPrincipal"))-Double.parseDouble(borrowPerStaMap.get("hasInterest"))+Double.parseDouble(borrowPerStaMap.get("recivedFI"));
				borrowPerStaMap.put("sypayCount", String.format("%.2f",sypayCount));
			}else{
				borrowPerStaMap.put("sypayCount","0.00");
			}
		}else{
			borrowPerStaMap.put("payCount", "0.00");
		}
		//资产统计计算（右）gfserviceAmount
		double ssAmount=0d;
		double sjsq=0d;
		double cb=0d;
		if(null!=userStatisMap&&null!=userStatisMap.get("borrowAmount")&&userStatisMap.get("borrowAmount").length()>0
		 &&null!=userStatisMap.get("gfserviceAmount")&&userStatisMap.get("gfserviceAmount").length()>0){
			ssAmount=Double.parseDouble(userStatisMap.get("borrowAmount"))-Double.parseDouble(userStatisMap.get("gfserviceAmount"));
			userStatisMap.put("ssAmount", String.format("%.2f",ssAmount));
			if(Double.parseDouble(userStatisMap.get("borrowAmount"))>0){
				sjsq=ssAmount/Double.parseDouble(userStatisMap.get("borrowAmount"));
				userStatisMap.put("sjsq",String.format("%.2f",sjsq*100));
				cb=(Double.parseDouble(userStatisMap.get("borrowAmount"))-ssAmount)/Double.parseDouble(userStatisMap.get("borrowAmount"));
				userStatisMap.put("cb",String.format("%.2f",cb*100));
			}else{
				userStatisMap.put("sjsq","0.00");
				userStatisMap.put("cb","0.00");
			}
			
		}else{
			userStatisMap.put("ssAmount","0.00");
		}
		
		request().setAttribute("borrowPerStaMap", borrowPerStaMap);
		request().setAttribute("userStatisMap", userStatisMap);
		
		List<Map<String, Object>> repaymentList= myHomeService.queryRepaymentList(user.getId());
		request().setAttribute("repaymentList", repaymentList);
		
		
		Map<String, String> homeMap = myHomeService.queryHomeInfo(user.getId());
		request().setAttribute("homeMap", homeMap);
			
		//个人头像
		Map<String, String> personalHeadMap = myHomeService.queryPersonalHead(user.getId());
		request().setAttribute("personalHeadMap", personalHeadMap);
		
		Map<String, String> accmountStatisMap = myHomeService.queryAccountStatisInfo(user.getId());
		request().setAttribute("accmountStatisMap", accmountStatisMap);
		//验证身份证是否已审核通过
		Map<String, String> materialsauth=validateService.querymaterialsauth(user.getId(), 1);
		request().setAttribute("materialsauth", materialsauth);
		//查询银行卡是否审核通过
		Map<String,String> yhmap = userService.queryFirstBankCardById(user.getId());
		request().setAttribute("yhmap", yhmap);
		//手机号码认证
		Map<String, String> sjmap = validateService.queryBaseDataById(user.getId());
		request().setAttribute("sjmap", sjmap);
		return "success";
	}
	
	/**
	 * @MethodName: homeBorrowPublishInit
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-18 下午08:53:29
	 * @Return:
	 * @Descb: 已经发布的借款初始化
	 * @Throws:
	 */
	public String homeBorrowPublishInit() {
		return "success";
	}

	/**
	 * @throws Exception
	 * @MethodName: loanStatisInit
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-26 下午02:57:19
	 * @Return:
	 * @Descb: 借款人信息统计
	 * @Throws:
	 */
	public String loanStatisInit() throws Exception {
		long userId=Convert.strToLong(request().getParameter("id"), -1L);
		//借款人借款统计
		Map<String, String> loanStatisMap = myHomeService.queryLoanStatis(userId);
		request().setAttribute("loanStatisMap", loanStatisMap);
		
		request().setAttribute("curPage", request("curPage"));
		request().setAttribute("id", userId);
		//借款人基本信息
		Map<String, String> homeMap = myHomeService.queryHomeInfo(userId);
		request().setAttribute("homeMap", homeMap);
		
		//借款人借款记录
		String borrowStatus = IConstants.BORROW_STATUS_4 + ","
							+ IConstants.BORROW_STATUS_5 + ",";
		return queryBrrowPublishListByUser(borrowStatus,userId);
	}

	/**
	 * @throws DataException
	 * @throws SQLException
	 * @MethodName: financeStatisInit
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-26 下午02:57:31
	 * @Return:
	 * @Descb: 理财统计
	 * @Throws:
	 */
	public String financeStatisInit() throws SQLException, DataException {
		User user = (User) session().getAttribute("user");
		Map<String, String> financeStatisMap = myHomeService
				.queryFinanceStatis(user.getId());
		request().setAttribute("financeStatisMap", financeStatisMap);
		return "success";
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowBackAcount
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-4-2 上午09:12:22
	 * @Return:
	 * @Descb: 查询借款回账
	 * @Throws:
	 */
	public String homeBorrowBackAcount() throws Exception {
		User user = (User) session().getAttribute("user");
		JSONObject obj = new JSONObject();
		String title = SqlInfusion.FilteSqlInfusion(paramMap.get("title") == null ? "" : paramMap
				.get("title"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(paramMap.get("publishTimeStart") == null ? ""
				: paramMap.get("publishTimeStart"));
		if (StringUtils.isNotBlank(publishTimeStart)) {
			publishTimeStart = publishTimeStart + " 00:00:00";
		}
		String publishTimeEnd = SqlInfusion.FilteSqlInfusion(paramMap.get("publishTimeEnd") == null ? ""
				: paramMap.get("publishTimeEnd"));
		if (StringUtils.isNotBlank(publishTimeStart)) {
			publishTimeEnd = publishTimeEnd + " 23:59:59";
		}
		Map<String, String> map = myHomeService.queryBackAcountStatis(user
				.getId(), publishTimeStart, publishTimeEnd, title);
		String allForPIOneMonth = map.get("allForPIOneMonth") == null ? "0"
				: map.get("allForPIOneMonth");
		String allForPIThreeMonth = map.get("allForPIThreeMonth") == null ? "0"
				: map.get("allForPIThreeMonth");
		String allForPIYear = map.get("allForPIYear") == null ? "0" : map
				.get("allForPIYear");
		String allForPI = map.get("allForPI") == null ? "0" : map
				.get("allForPI");
		obj.put("allForPIOneMonth", allForPIOneMonth);
		obj.put("allForPIThreeMonth", allForPIThreeMonth);
		obj.put("allForPIYear", allForPIYear);
		obj.put("allForPI", allForPI);
		JSONUtils.printObject(obj);
		return null;
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowInvestList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-26 下午08:40:13
	 * @Return:
	 * @Descb: 投资借款列表
	 * @Throws:
	 */
	public String homeBorrowInvestList() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));

		String type = "1";
		String borrowStatus = "";
		if ("1".equals(type)) {
			borrowStatus = IConstants.BORROW_STATUS_4 + ","
					+ IConstants.BORROW_STATUS_5;
		} else if ("2".equals(type)) {
			borrowStatus = "" + IConstants.BORROW_STATUS_2;
		}
		String title = SqlInfusion.FilteSqlInfusion(request("title"));
		String publishTimeStart =SqlInfusion.FilteSqlInfusion( request("publishTimeStart"));
		String publishTimeEnd =SqlInfusion.FilteSqlInfusion( request("publishTimeEnd"));
		myHomeService.queryBorrowInvestByCondition(title, publishTimeStart,
				publishTimeEnd, borrowStatus, user.getId(), pageBean);
		this.setRequestToParamMap();
		return SUCCESS;
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowInvestList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-26 下午08:40:13
	 * @Return:
	 * @Descb: 投资借款列表
	 * @Throws:
	 */
	public String homeBorrowTenderInList() throws Exception {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		String borrowStatus = IConstants.BORROW_STATUS_2 + "";

		String title = SqlInfusion.FilteSqlInfusion(request("title"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(request("publishTimeStart"));
		String publishTimeEnd = SqlInfusion.FilteSqlInfusion(request("publishTimeEnd"));
		myHomeService.queryBorrowInvestByCondition(title, publishTimeStart,
				publishTimeEnd, borrowStatus, user.getId(), pageBean);
		this.setRequestToParamMap();
		return SUCCESS;
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowRecycleList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-26 下午08:41:47
	 * @Return:
	 * @Descb: 待回收借款列表
	 * @Throws:
	 */
	public String homeBorrowRecycleList() throws Exception {
		User user = (User) session().getAttribute("user");
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		String title =SqlInfusion.FilteSqlInfusion( request("title"));
		myHomeService.queryBorrowRecycleByCondition(title, user.getId(),
				pageBean);
		this.setRequestToParamMap();
		return "success";
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowRecycledList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-27 下午01:40:27
	 * @Return:
	 * @Descb: 已回收的借款
	 * @Throws:
	 */
	public String homeBorrowRecycledList() throws Exception {
		User user = (User) session().getAttribute("user");
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		String title = SqlInfusion.FilteSqlInfusion(request("title"));
		myHomeService.queryBorrowRecycledByCondition(title, user.getId(),
				pageBean);
		this.setRequestToParamMap();
		return "success";
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowForpayDetail
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-27 下午06:53:03
	 * @Return:
	 * @Descb: 查询投资人回收中借款还款详情
	 * @Throws:
	 */
	public String homeBorrowForpayDetail() throws Exception {
		User user = (User) session().getAttribute("user");
		String id = SqlInfusion.FilteSqlInfusion(request().getParameter("id") == null ? "" : request()
				.getParameter("id"));
		// add by houli
		String iid = SqlInfusion.FilteSqlInfusion(request().getParameter("iid") == null ? "" : request()
				.getParameter("iid"));
		long idLong = Convert.strToLong(id, -1);
		long iidLong = Convert.strToLong(iid, -1);
		List<Map<String, Object>> listMap = myHomeService
				.queryBorrowForpayById(idLong, user.getId(), iidLong);
		/*
		 * DecimalFormat df_two = new DecimalFormat("#0.00"); //-----add by
		 * houli 2013-04-25将数字进行格式化，保留两位小数 for(Map<String,Object> map : listMap
		 * ){
		 * 
		 * map.put("forpayPrincipal", df_two.format(
		 * map.get("forpayPrincipal"))); map.put("forpayInterest",
		 * df_two.format( map.get("forpayInterest")));
		 * map.put("principalBalance", df_two.format(
		 * map.get("principalBalance"))); map.put("manage", df_two.format(
		 * map.get("manage"))); map.put("earn", String.format("%.2f",
		 * map.get("earn"))); } //
		 */request().setAttribute("listMap", listMap);
		return "success";
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowHaspayDetail
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-27 下午06:57:20
	 * @Return:
	 * @Descb: 查询投资人已回收借款还款详情
	 * @Throws:
	 */
	public String homeBorrowHaspayDetail() throws Exception {
		User user = (User) session().getAttribute("user");
		String id = SqlInfusion.FilteSqlInfusion(request().getParameter("id") == null ? "" : request()
				.getParameter("id"));
		String iid = SqlInfusion.FilteSqlInfusion(request().getParameter("iid") == null ? "" : request()
				.getParameter("iid"));

		long idLong = Convert.strToLong(id, -1);
		long iidLong = Convert.strToLong(iid, -1);
		List<Map<String, Object>> listMap = myHomeService
				.queryBorrowHaspayById(idLong, user.getId(), iidLong);
		request().setAttribute("listMap", listMap);
		return "success";
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowBackAcountList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-26 下午08:43:24
	 * @Return:
	 * @Descb: 借款回账查询列表
	 * @Throws:
	 */
	public String homeBorrowBackAcountList() throws Exception {
		User user = (User) session().getAttribute("user");

		Map<String, String> backAcountStatisMap = myHomeService
				.queryBackAcountStatis(user.getId(), "", "", "");
		request().setAttribute("backAcountStatisMap", backAcountStatisMap);
		// 回账类型
		request().setAttribute("type", "5");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		String title = SqlInfusion.FilteSqlInfusion(request("title"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(request("publishTimeStart"));
		String publishTimeEnd =SqlInfusion.FilteSqlInfusion( request("publishTimeEnd"));
		myHomeService.queryBorrowBackAcountByCondition(title, publishTimeStart,
				publishTimeEnd, user.getId(), pageBean);

		this.setRequestToParamMap();
		return SUCCESS;
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowPublishList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-18 下午09:03:01
	 * @Return:
	 * @Descb: 审核中的借款
	 * @Throws:
	 */
	public String homeBorrowAuditList() throws Exception {
		String borrowStatus = IConstants.BORROW_STATUS_1 + ","
				+ IConstants.BORROW_STATUS_3;
		return queryBrrowPublishList(borrowStatus);
	}

	/**
	 * @throws Exception
	 * @MethodName: homeBorrowPublishList
	 * @Param: FrontMyHomeAction
	 * @Author: gang.lv
	 * @Date: 2013-3-18 下午09:03:01
	 * @Return:
	 * @Descb: 已经发布的借款列表
	 * @Throws:
	 */
	public String homeBorrowingList() throws Exception {
		String borrowStatus = "" + IConstants.BORROW_STATUS_2;
		return queryBrrowPublishList(borrowStatus);
	}
	/**
	 * 当前登录人借款列表
	 * @param borrowStatus
	 * @return
	 * @throws Exception
	 */
	private String queryBrrowPublishList(String borrowStatus) throws Exception {
		User user = (User) session().getAttribute("user");
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		pageBean.setPageSize(IConstants.PAGE_SIZE_10);
		String title = SqlInfusion.FilteSqlInfusion(request("title"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(request("publishTimeStart"));
		String publishTimeEnd = SqlInfusion.FilteSqlInfusion(request("publishTimeEnd"));
		myHomeService.queryBorrowFinishByCondition(title, publishTimeStart,
				publishTimeEnd, borrowStatus, user.getId(), pageBean);
		this.setRequestToParamMap();
		return SUCCESS;
	}
	/**
	 * 根据用户查询借款列表
	 * @param borrowStatus
	 * @return
	 * @throws Exception
	 */
	private String queryBrrowPublishListByUser(String borrowStatus,Long userId) throws Exception {
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		pageBean.setPageSize(100);
		String title =SqlInfusion.FilteSqlInfusion( request("title"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(request("publishTimeStart"));
		String publishTimeEnd = SqlInfusion.FilteSqlInfusion(request("publishTimeEnd"));
		myHomeService.queryBorrowFinishByCondition(title, publishTimeStart,
				publishTimeEnd, borrowStatus, userId, pageBean);
		this.setRequestToParamMap();
		return SUCCESS;
	}
	
	/***
	 * 进入借款人安全中心
	 */
	public String jkpersafecenter(){
		User user = (User) session().getAttribute("user");
		// 根据用户ID查询安全问题
		Map<String, String> map;
		try {
			map = userService.queryQuestion(user.getId());
			request().setAttribute("map", map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	/***
	 * 借款人安全中心---密码修改
	 * @return
	 */
	public String jkpersafepassword(){
		return SUCCESS;
	}
	/***
	 * 借款人安全中心---邮箱修改
	 * @return
	 */
	public String jkpersafemail(){
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		try {
			paramMap = userService.queryUserById(user.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		String email = SqlInfusion.FilteSqlInfusion(paramMap.get("email") + "");
		String flag = "1";
		session().setAttribute("DEMO", IConstants.ISDEMO);
		return SUCCESS;
	}
	/***
	 * 发送邮件
	 * @return
	 * @throws Exception 
	 */
	public String sendEmail() throws Exception{
		JSONObject obj = new JSONObject();
		Map<String, String> map = null;
		String username = "";
		Long userId = null;
		String email = SqlInfusion.FilteSqlInfusion(paramMap.get("email"));
		if (StringUtils.isBlank(email)) {
			obj.put("mailAddress", "0");
			JSONUtils.printObject(obj);
			return null;
		}
		long result1 = userService.isExistEmailORUserName(email, null);
		if (result1 > 0) { // email重复
			obj.put("mailAddress", "4");
			JSONUtils.printObject(obj);
			return null;
		}
		// ===截取emal后面地址
		int dd = email.indexOf("@");
		String mailAddress = null;
		if (dd >= 0) {
			mailAddress = "mail." + email.substring(dd + 1);
		}

		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user != null) {
			DesSecurityUtil des = new DesSecurityUtil();
			String key1 = des.encrypt(user.getId() + "");
			String key2 = des.encrypt(new Date().getTime() + "");
			String key3 = email;
			String Name = user.getUserName();
			String url = getPath(); // request().getRequestURI();
			String VerificationUrl = url + "emailSuccess.do?key=" + key1 + "-"
					+ key2 + "-" + key3;
			sendMailService.SendUserEmailSetInUser(VerificationUrl, Name, email);
			obj.put("mailAddress", mailAddress);
			JSONUtils.printObject(obj);
			return null;
		}
		return null;
	}
	/***
	 * 绑定邮箱
	 * @return
	 * @throws Exception 
	 */
	public String emailSuccess() throws Exception{
		String key = SqlInfusion.FilteSqlInfusion(request("key").trim());
		String msg = "邮箱验证失败";
		String[] keys = key.split("-");
		if (3 == keys.length) {
			DesSecurityUtil des = new DesSecurityUtil();
			Long userId = Convert
					.strToLong(des.decrypt(keys[0].toString()), -1);
			String dateTime = des.decrypt(keys[1].toString());
			long curTime = new Date().getTime();
			String emial = keys[2].toString();
			Pattern p = Pattern
					.compile("^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$");
			Matcher matcher = p.matcher(emial);
			if (!matcher.matches()) {
				paramMap.put("msg", "邮箱格式错误");
			} else {
				// 校验邮箱的唯一性
				long result1 = userService.isExistEmailORUserName(emial, null);
				if (result1 > 0) { // email重复
					paramMap.put("msg", "该邮箱已被绑定,请重新输入");
				} else {
					// 当用户点击注册时间小于10分钟
					if (curTime - Long.valueOf(dateTime) < 10 * 60 * 1000) {
						long result = userService.updateEmalByid(userId, emial);
						if (result < 0) {
							paramMap.put("msg", "邮箱绑定失败");
						} else {
							paramMap.put("msg", "恭喜您，"+emial+"邮箱绑定成功!");
							Map<String, String> map = userService
									.queEmailUser(userId);
							String username = map.get("username") + "";
							bbsRegisterService.doUpdateEmailByAsynchronousMode(
									username, emial);
							
							User user=(User) session().getAttribute("user");
							user.setEmail(emial);
							session().setAttribute("user", user);
						}
						return SUCCESS;
					} else {
						msg = "连接失效,<strong>请重新绑定</a></strong>";
						paramMap.put("msg", msg);
					}
				}
			}
		}
		return SUCCESS;
	}

	public MyHomeService getMyHomeService() {
		return myHomeService;
	}
	
	public OperationLogService getOperationLogService() {
		return operationLogService;
	}

	public void setOperationLogService(OperationLogService operationLogService) {
		this.operationLogService = operationLogService;
	}

	public void setMyHomeService(MyHomeService myHomeService) {
		this.myHomeService = myHomeService;
	}

	public SelectedService getSelectedService() {
		return selectedService;
	}

	public void setSelectedService(SelectedService selectedService) {
		this.selectedService = selectedService;
	}
	
	public SendMailService getSendMailService() {
		return sendMailService;
	}

	public void setSendMailService(SendMailService sendMailService) {
		this.sendMailService = sendMailService;
	}

	public void setFrontpayService(FrontMyPaymentService frontpayService) {
		this.frontpayService = frontpayService;
	}
	
	public ValidateService getValidateService() {
		return validateService;
	}

	public void setValidateService(ValidateService validateService) {
		this.validateService = validateService;
	}

	public BBSRegisterService getBbsRegisterService() {
		return bbsRegisterService;
	}

	public void setBbsRegisterService(BBSRegisterService bbsRegisterService) {
		this.bbsRegisterService = bbsRegisterService;
	}

	public HomeInfoSettingService getHomeInfoSettingService() {
		return homeInfoSettingService;
	}

	public void setHomeInfoSettingService(
			HomeInfoSettingService homeInfoSettingService) {
		this.homeInfoSettingService = homeInfoSettingService;
	}

	public List<Map<String, Object>> getBorrowDeadlineList() throws Exception {
		if (borrowDeadlineList == null) {
			// 借款期限列表
			borrowDeadlineList = selectedService.borrowDeadline();
		}
		return borrowDeadlineList;
	}

	

	public List<Operator> getCheckList() {
		return checkList;
	}

	//历史投资
	public String investSuccessedRecord() throws SQLException, DataException {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		
		String title=SqlInfusion.FilteSqlInfusion(request("title"));
		String publisher = SqlInfusion.FilteSqlInfusion(request("publisher"));
		String publishTimeStart =SqlInfusion.FilteSqlInfusion( request("publishTimeStart"));
		String publishTimeEnd =SqlInfusion.FilteSqlInfusion( request("publishTimeEnd"));
		
		paramMap.put("title",SqlInfusion.FilteSqlInfusion(request("title")));
		paramMap.put("publisher", publisher);
		paramMap.put("publishTimeStart", publishTimeStart);
		paramMap.put("publishTimeEnd", publishTimeEnd);
		
		
		myHomeService.queryInvestSuccessedRecord(title, publishTimeStart, publishTimeEnd, user.getId(), pageBean,publisher);
		
		List<Map<String,Object>> pageList = pageBean.getPage();
		if(pageList!=null&&pageList.size()>0){
			for (int i = 0; i < pageList.size(); i++) {
				Map<String,Object> map = pageList.get(i);
				double realAmount = Convert.strToDouble(map.get("realAmount").toString(),0);
				double hasPI = Convert.strToDouble(map.get("hasPI").toString(),0);
				map.put("realAmount", String.format("%.2f", realAmount));
				map.put("hasPI", String.format("%.2f", hasPI));
			}
		}
		
		//Map map=myHomeService.queryAmount(user.getId(),"success");
		//request().setAttribute("map", map);
		/*this.setRequestToParamMap();*/
		request().setAttribute("userId", user.getId());
		return SUCCESS;
	}
	public String queryUserRecordAll() throws Exception{
		User user =this.getUser();
		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		operationLogService.queryUserRecordAll(pageBean, user.getUserName());
		int pageNum = (int) (pageBean.getPageNum() - 1)
				* pageBean.getPageSize();
		request().setAttribute("pageNum", pageNum);
		this.setRequestToParamMap();
		return SUCCESS;
	}
	//当前投资
	public String investCurrentRecord() throws SQLException, DataException {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		
		String title=SqlInfusion.FilteSqlInfusion(request("title"));
		String publisher = SqlInfusion.FilteSqlInfusion(request("publisher"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(request("publishTimeStart"));
		String publishTimeEnd = SqlInfusion.FilteSqlInfusion(request("publishTimeEnd"));
		
		paramMap.put("title",SqlInfusion.FilteSqlInfusion(request("title")));
		paramMap.put("publisher", publisher);
		paramMap.put("publishTimeStart", publishTimeStart);
		paramMap.put("publishTimeEnd", publishTimeEnd);
		
		
		myHomeService.queryInvestCurrentRecord(title, publishTimeStart, publishTimeEnd, user.getId(), pageBean,publisher);
		
		List<Map<String,Object>> pageList = pageBean.getPage();
		if(pageList!=null&&pageList.size()>0){
			for (int i = 0; i < pageList.size(); i++) {
				Map<String,Object> map = pageList.get(i);
				double realAmount = Convert.strToDouble(map.get("realAmount").toString(),0);
				double recievedInterest = Convert.strToDouble(map.get("recievedInterest").toString(),0);
				double notPI = Convert.strToDouble(map.get("notPI").toString(),0);
				map.put("realAmount", String.format("%.2f", realAmount));
				map.put("notPI", String.format("%.2f", notPI));
				if(map.get("isDayThe").toString().equals("1")){
					int deadline = Convert.strToInt(map.get("deadline").toString(), 0);
					recievedInterest = recievedInterest/deadline;
				}
				map.put("recievedInterest", String.format("%.2f", recievedInterest));
				//借款期限
				String repayDate="";
				if(null!=map.get("repayDate")){
					repayDate = map.get("repayDate").toString();
					String deadline = map.get("deadline").toString();
					if(map.get("isDayThe").toString().equals("1")){	//不是天标
						String theMonth = repayDate.substring(5, 7);
						String theYear = repayDate.substring(0,4);
						int month = Integer.parseInt(theMonth);
						if(!map.get("paymentMode").toString().equals("4")){
							month = Integer.parseInt(theMonth) + Integer.parseInt(deadline)-1;
						}
						if(month/12>0){
							theYear = Integer.parseInt(theYear) + month/12+"";
							theMonth = month -12*(month/12)+"";
						}else{
							theMonth = month+"";
						}
						if(theMonth.length()==1){
							theMonth = "0"+theMonth;
						}
						repayDate = theYear+"-"+theMonth+repayDate.substring(7,10);
					}
				}
				/*else{	//天标
					String theMonth = repayDate.substring(5, 7);
					String theDay = repayDate.substring(8, 10);
					String theYear = repayDate.substring(0,4);
					int endDay = Integer.parseInt(theDay)+Integer.parseInt(deadline);
					if(endDay>30){
						theMonth = Integer.parseInt(theMonth)+1+"";
						endDay = endDay - 30;
					}
					if(Integer.parseInt(theMonth)/12>1){
						theYear = Integer.parseInt(theYear) + Integer.parseInt(theMonth)/12+"";
						theMonth = Integer.parseInt(theMonth) -12*(Integer.parseInt(theMonth)/12)+"";
					}
					if(theMonth.length()==1){
						theMonth = "0"+theMonth;
					}
					theDay = endDay+"";
					if(theDay.length()==1){
						theDay = "0"+theDay;
					}
					repayDate = theYear+"-"+theMonth+"-"+theDay;
				}*/
				map.put("finalRepayDate", repayDate);
			}
		}
		
		
//		Map map=myHomeService.queryAmount(user.getId(),"current");
//		request().setAttribute("map", map);
		request().setAttribute("userId", user.getId());
		return SUCCESS;
	}
	//债权记录
	public String debtRecord() throws SQLException, DataException {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		
		String title=SqlInfusion.FilteSqlInfusion(request("title"));
		String publisher = SqlInfusion.FilteSqlInfusion(request("publisher"));
		String publishTimeStart =SqlInfusion.FilteSqlInfusion( request("publishTimeStart"));
		String publishTimeEnd =SqlInfusion.FilteSqlInfusion( request("publishTimeEnd"));
		
		paramMap.put("title",SqlInfusion.FilteSqlInfusion(request("title")));
		paramMap.put("publisher", publisher);
		paramMap.put("publishTimeStart", publishTimeStart);
		paramMap.put("publishTimeEnd", publishTimeEnd);
		
		
		myHomeService.queryDebtRecord(title, publishTimeStart, publishTimeEnd, user.getId(), pageBean,publisher);
		//Map map=myHomeService.queryAmount(user.getId(),"success");
		//request().setAttribute("map", map);
		/*this.setRequestToParamMap();*/
		return SUCCESS;
	}
	
	/***
	 * 查看债权转让合同
	 * @return
	 * @throws Exception 
	 */
	public String zqzr() throws Exception{
		Long investId = Convert.strToLong(request("investId"),-1);
		Map<String,String> map = myHomeService.debtHeTong(investId);
		Map<String,String> regmap = publicModelService.getAgreementDetail(2, 1);
		request().setAttribute("regMap", regmap);
		request().setAttribute("map", map);
		return SUCCESS;
	}
	
	//详细统计
	public String investDetailCount() throws Exception {
		User user = (User) session().getAttribute("user");

		//各数量总额统计
		Map<String, String> accmountStatisMap = myHomeService.queryAccountStatisInfo(user.getId());
		request().setAttribute("map", accmountStatisMap);
		
		//计算加权收益
		Map<String, String> weightingRateMap = myHomeService.queryWeightingRate(user.getId());
		request().setAttribute("weightingRateMap", weightingRateMap);

		//按风险评定等级进行统计
		Map<String, String> A=myHomeService.queryCreditA();
		Map<String, String> B=myHomeService.queryCreditB();
		Map<String, String> C=myHomeService.queryCreditC();
		Map<String, String> D=myHomeService.queryCreditD();
		Map<String, String> E=myHomeService.queryCreditE();
		Map<String, String> HR=myHomeService.queryCreditHR();
		//统计总的投资记录条数
		if(HR.size()!=0&&HR!=null){
			Map<String, String> countsMap=myHomeService.queryAllInvestCount();
			request().setAttribute("counts", countsMap.get("counts"));
		}
		request().setAttribute("A", A.get("A"));
		request().setAttribute("B", B.get("B"));
		request().setAttribute("C", C.get("C"));
		request().setAttribute("D", D.get("D"));
		request().setAttribute("E", E.get("E"));
		request().setAttribute("HR",  HR.get("HR"));
		
		return SUCCESS;
	}
	
	public FundrecordService getFundrecordService() {
		return fundrecordService;
	}

	public void setFundrecordService(FundrecordService fundrecordService) {
		this.fundrecordService = fundrecordService;
	}
	public NewsAndMediaReportService getNewsService() {
		return newsService;
	}

	public void setNewsService(NewsAndMediaReportService newsService) {
		this.newsService = newsService;
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	//偿还中的借款
	public String borrowPayingRecord() throws SQLException, DataException {
		User user = (User) session().getAttribute("user");

		pageBean.setPageNum(SqlInfusion.FilteSqlInfusion(request("curPage")));
		
		String title=SqlInfusion.FilteSqlInfusion(request("title"));
		String publisher = SqlInfusion.FilteSqlInfusion(request("publisher"));
		String publishTimeStart = SqlInfusion.FilteSqlInfusion(request("publishTimeStart"));
		String publishTimeEnd = SqlInfusion.FilteSqlInfusion(request("publishTimeEnd"));
		
		paramMap.put("title",SqlInfusion.FilteSqlInfusion(request("title")));
		paramMap.put("publisher", publisher);
		paramMap.put("publishTimeStart", publishTimeStart);
		paramMap.put("publishTimeEnd", publishTimeEnd);
		
		
		myHomeService.queryInvestSuccessedRecord(title, publishTimeStart, publishTimeEnd, user.getId(), pageBean,publisher);
		//Map map=myHomeService.queryAmount(user.getId(),"success");
		//request().setAttribute("map", map);
		/*this.setRequestToParamMap();*/
		return SUCCESS;
	}

	public void signToday() throws Exception{
		User user=(User)session().getAttribute("user");
		
		Map<String, String> map = myHomeService.signToday(user.getId());
		long r = Convert.strToLong(map.get("ret"), -1);
		
		JSONObject obj = new JSONObject();
		obj.put("code", r);
		obj.put("msg", map.get("ret_desc"));
		JSONUtils.printObject(obj);
	    
	}
	
	public void querySignRecord() throws Exception{
		User user=(User)session().getAttribute("user");
		Map<String, String> map  = myHomeService.queryMySignRecord(user.getId());
		JSONObject obj = new JSONObject();
		obj.put("record", map);
		JSONUtils.printObject(obj);
	}
}
